<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { QTable, QForm } from '@meetjs/element-plus-kit'
import { ElMessage, ElMessageBox } from 'element-plus'
import { tableColumns, formOptions } from './config'
import { getTeamExperienceApi, addTeamExperienceApi, updateTeamExperienceApi, deleteTeamExperienceApi } from './api'
import type { TeamExperienceRecord } from './types'
import type { AthleteTeamExp } from '@/api/athlete/types'
import { ATHLETE_DICT } from '@/constants'
import { useDict } from '@/composables/useDict'

// Props
interface Props {
	athleteId: string | number | undefined
	readonly?: boolean
	data?: any[] // 从父组件传入的数据
}

const props = withDefaults(defineProps<Props>(), {
	readonly: false,
	data: () => []
})

const { getDictLabel } = useDict([ATHLETE_DICT.TRAIN_TYPE])

// 数据状态
const loading = ref(false)
const tableData = ref<TeamExperienceRecord[]>([])

// 弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('新增集训经历')
const isEdit = ref(false)

// 表单数据
const formData = ref<Partial<AthleteTeamExp>>({})
const formRef = ref()

// 刷新表格数据（在增删改后调用API重新获取）
const refreshTableData = async () => {
	try {
		loading.value = true
		const res = await getTeamExperienceApi(props.athleteId!)

		if (res.data && Array.isArray(res.data)) {
			tableData.value = res.data.map((item: any) => ({
				...item,
				trainTypeLabel: getDictLabel(ATHLETE_DICT.TRAIN_TYPE, item.trainType)
			}))
		} else {
			tableData.value = []
		}
	} catch (error) {
		console.error('刷新集训经历失败:', error)
		ElMessage.error('刷新数据失败')
	} finally {
		loading.value = false
	}
}

// 新增
const handleAdd = () => {
	isEdit.value = false
	dialogTitle.value = '新增集训经历'
	formData.value = { infoId: typeof props.athleteId === 'string' ? parseInt(props.athleteId) : props.athleteId }
	dialogVisible.value = true
}

// 编辑
const handleEdit = (row: TeamExperienceRecord) => {
	isEdit.value = true
	dialogTitle.value = '编辑集训经历'
	formData.value = { ...row } as any
	dialogVisible.value = true
}

// 删除
const handleDelete = async (row: TeamExperienceRecord) => {
	try {
		await ElMessageBox.confirm(`确定要删除这条集训经历吗？`, '删除确认', { type: 'warning' })

		await deleteTeamExperienceApi(row.id!)
		ElMessage.success('删除成功')
		refreshTableData()
	} catch (error) {
		if (error !== 'cancel') {
			ElMessage.error('删除失败')
		}
	}
}

// 关闭弹窗时的处理
const handleClose = () => {
	formRef.value?.resetFields()
	formRef.value?.clearValidate()
}

// 保存表单
const handleSave = async () => {
	formRef.value?.validate(async (valid: boolean) => {
		if (!valid) {
			// 验证失败，直接返回，不继续执行API调用
			return
		}

		try {
			loading.value = true

			if (isEdit.value) {
				await updateTeamExperienceApi(formData.value.id!, formData.value)
				ElMessage.success('更新成功')
			} else {
				await addTeamExperienceApi(formData.value)
				ElMessage.success('添加成功')
			}

			dialogVisible.value = false
			refreshTableData()
		} catch (error) {
			console.error('保存失败:', error)
			ElMessage.error('保存失败')
		} finally {
			loading.value = false
		}
	})
}

watch(() => props.athleteId, refreshTableData)
</script>

<template>
	<div class="team-experience">
		<!-- 表头 -->
		<div class="flex items-center justify-between mb-4">
			<h3 class="font-semibold text-lg">集训及入队经历</h3>
			<el-button
				v-if="!readonly"
				type="primary"
				@click="handleAdd"
			>
				新增集训经历
			</el-button>
		</div>

		<!-- 数据表格 -->
		<QTable
			:data="tableData"
			:columns="tableColumns"
			:loading="loading"
			:pagination="false"
		>
			<!-- 操作列 -->
			<template
				v-if="!readonly"
				#action="{ row }"
			>
				<el-button
					type="primary"
					link
					@click="handleEdit(row)"
				>
					编辑
				</el-button>
				<el-button
					type="danger"
					link
					@click="handleDelete(row)"
				>
					删除
				</el-button>
			</template>
		</QTable>

		<!-- 编辑弹窗 -->
		<ElDialog
			v-model="dialogVisible"
			:title="dialogTitle"
			:close-on-click-modal="false"
			width="800px"
			@close="handleClose"
		>
			<div v-loading="loading">
				<QForm
					ref="formRef"
					label-width="120px"
					:model="formData"
					:form-options="formOptions"
				/>
			</div>

			<template #footer>
				<div class="flex items-center justify-end gap-4">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button
						type="primary"
						:loading="loading"
						@click="handleSave"
					>
						确定
					</el-button>
				</div>
			</template>
		</ElDialog>
	</div>
</template>

<style scoped lang="scss">
.team-experience {
	padding: 20px;
	background: #ffffff;
	border-radius: 6px;
	box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
}
</style>
